package com.group.yztcedu.playlive.main.me.View;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.group.yztcedu.playlive.R;
import com.group.yztcedu.playlive.bean.MyDataBean;
import com.group.yztcedu.playlive.db.MySQLiteOpenHelper;
import com.group.yztcedu.playlive.utils.CropHandler;
import com.group.yztcedu.playlive.utils.CropHelper;
import com.group.yztcedu.playlive.utils.CropParams;
import com.group.yztcedu.playlive.utils.RoundImageUtil;
import com.group.yztcedu.playlive.widget.CircleTransform;

import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MeSetActivity extends AppCompatActivity implements CropHandler{

    @BindView(R.id.me_set_back)
    ImageView meSetBack;
    @BindView(R.id.me_set_headImage_logo)
    ImageView meSetHeadImageLogo;
    @BindView(R.id.me_set_headImage)
    RelativeLayout meSetHeadImage;
    @BindView(R.id.me_head_set_detil_namedetil)
    TextView meHeadSetDetilNamedetil;
    @BindView(R.id.me_head_set_name)
    RelativeLayout meHeadSetName;
    @BindView(R.id.me_head_set_detil_sexdetil)
    TextView meHeadSetDetilSexdetil;
    @BindView(R.id.me_head_set_sex)
    RelativeLayout meHeadSetSex;
    @BindView(R.id.me_head_set_detil_persondetil)
    TextView meHeadSetDetilPersondetil;
    @BindView(R.id.me_head_set_detil)
    RelativeLayout meHeadSetDetil;
    @BindView(R.id.me_set_exit)
    TextView meSetExit;

    private View parentView;
    private View view;
    private PopupWindow popupWindow;
    private Button btn_paizhao_popup_window;
    private Button btn_selector_popup_window;
    private Button btn_cancel_popup_window;
    private CropParams mCropParams;
    private static String[] PERMISSIONS_ALL = {
            Manifest.permission.CAMERA,
            Manifest.permission_group.STORAGE};

    final private int REQUEST_CODE = 123;
    private AlertDialog.Builder builder;
    private EditText etName;
    private MyDataBean myDataBean;
    private String Imageuri;
    private String username;
    private String usersex;
    private String userdetil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_me_set);
        ButterKnife.bind(this);
//        Imageuri  username  usersex  userdetil
        getData("Imageuri");
        getData("username");
        getData("usersex");
        getData("userdetil");
        MySQLiteOpenHelper mySQLiteOpenHelper = new MySQLiteOpenHelper(MeSetActivity.this);
        myDataBean = new MyDataBean();
        mCropParams = new CropParams(this);
        parentView = LayoutInflater.from(this).inflate(R.layout.activity_me_set,null);
        view = LayoutInflater.from(this).inflate(R.layout.camera_popupwindow, null);
        btn_paizhao_popup_window = (Button) view.findViewById(R.id.btn_paizhao_popup_window);
        btn_selector_popup_window = (Button) view.findViewById(R.id.btn_selector_popup_window);
        btn_cancel_popup_window = (Button) view.findViewById(R.id.btn_cancel_popup_window);
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        btn_cancel_popup_window.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (popupWindow != null) {
                    popupWindow.dismiss();
                }
            }
        });

        btn_paizhao_popup_window.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MeSetActivity.this,"拍照",Toast.LENGTH_SHORT).show();
                if (ContextCompat.checkSelfPermission(MeSetActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //进入到这里代表没有权限.

                    if(ActivityCompat.shouldShowRequestPermissionRationale(MeSetActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE)){
                        //已经禁止提示了
                        Toast.makeText(MeSetActivity.this, "您已禁止该权限，需要重新开启。", Toast.LENGTH_SHORT).show();
                    }else{
                        ActivityCompat.requestPermissions(MeSetActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
                    }

                } else {
                    mCropParams.enable = true;
                    mCropParams.compress = false;
                    Intent intent = CropHelper.buildCameraIntent(mCropParams);
                    startActivityForResult(intent, CropHelper.REQUEST_CAMERA);
                    popupWindow.dismiss();
                }

            }
        });

        btn_selector_popup_window.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MeSetActivity.this,"选取",Toast.LENGTH_SHORT).show();
                if (ContextCompat.checkSelfPermission(MeSetActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //进入到这里代表没有权限.

                    if(ActivityCompat.shouldShowRequestPermissionRationale(MeSetActivity.this,Manifest.permission.READ_EXTERNAL_STORAGE)){
                        //已经禁止提示了
                        Toast.makeText(MeSetActivity.this, "您已禁止该权限，需要重新开启。", Toast.LENGTH_SHORT).show();
                    }else{
                        ActivityCompat.requestPermissions(MeSetActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE);

                    }

                } else {
                    mCropParams.enable = true;
                    mCropParams.compress = false;
                    Intent intent = CropHelper.buildGalleryIntent(mCropParams);
                    startActivityForResult(intent, CropHelper.REQUEST_CROP);
                    popupWindow.dismiss();
                }
            }
        });
    }

    @OnClick({R.id.me_set_back, R.id.me_set_headImage, R.id.me_head_set_name, R.id.me_head_set_sex, R.id.me_head_set_detil, R.id.me_set_exit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.me_set_back:
                finish();
                break;
            case R.id.me_set_headImage:
                popupWindow.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.me_head_set_name:
                initnameDiolog();
                break;
            case R.id.me_head_set_sex:
                initsexDiolog();
                break;
            case R.id.me_head_set_detil:
                initdetilDiolog();
                break;
            case R.id.me_set_exit:
                break;
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    private void initnameDiolog() {
        builder = new AlertDialog.Builder(this);
        // 设置自定义的标题
        // 自定义内容视图
        View view = getLayoutInflater().inflate(R.layout.me_head_set_name_dialog, null);
         etName = (EditText) view.findViewById(R.id.set_name_detil);
        // EditText etPass = (EditText) view.findViewById(R.id.et_bottom);
        builder.setView(view);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                username = String.valueOf(etName.getText());
                meHeadSetDetilNamedetil.setText(username);
                sharedPre("username",username);
                Toast.makeText(MeSetActivity.this,"修改成功",Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(MeSetActivity.this,"用户取消求改",Toast.LENGTH_SHORT).show();
            }
        });
        builder.show();
    }
    private void initsexDiolog() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // 设置自定义的标题
        // 自定义内容视图
        View view = getLayoutInflater().inflate(R.layout.me_head_set_sex_dialog, null);
        RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.sex_group);
        final RadioButton radioButton1 = (RadioButton) radioGroup.findViewById(R.id.man);
        final RadioButton radioButton2 = (RadioButton) radioGroup.findViewById(R.id.woman);
        final RadioButton radioButton3 = (RadioButton) radioGroup.findViewById(R.id.elsesex);
        builder.setView(view);
        final AlertDialog show = builder.show();
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i){
                    case R.id.man:
                        usersex = (String) radioButton1.getText();
                        meHeadSetDetilSexdetil.setText(usersex);
                        sharedPre("usersex",usersex);
                        show.dismiss();
                        break;
                    case R.id.woman:
                        usersex = (String) radioButton2.getText();
                        meHeadSetDetilSexdetil.setText(usersex);
                        sharedPre("usersex",usersex);
                        show.dismiss();
                        break;
                    case R.id.elsesex:
                        usersex = (String) radioButton3.getText();
                        meHeadSetDetilSexdetil.setText(usersex);
                        sharedPre("usersex",usersex);
                        show.dismiss();
                        break;
                }
            }
        });
    }
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    private void initdetilDiolog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // 设置自定义的标题
        // 自定义内容视图
        View view = getLayoutInflater().inflate(R.layout.me_head_set_detil_dialog, null);
        final EditText detil = (EditText) view.findViewById(R.id.set_user_detil);
        builder.setView(view);

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                userdetil = String.valueOf(detil.getText());
                if(userdetil.equals(detil.getHint())){
                    Toast.makeText(MeSetActivity.this,"未设置信息，默认为空",Toast.LENGTH_SHORT).show();
                    meHeadSetDetilPersondetil.setText("");
                }else{
                    Toast.makeText(MeSetActivity.this,"修改成功",Toast.LENGTH_SHORT).show();
                    meHeadSetDetilPersondetil.setText(userdetil);
                    sharedPre("userdetil",userdetil);
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(MeSetActivity.this,"用户取消修改",Toast.LENGTH_SHORT).show();

            }
        });
        builder.show();
    }
    @Override
    public void onPhotoCropped(Uri uri) {
        // Original or Cropped uri
        if (!mCropParams.compress)
            Log.i("TAG", "onPhotoCropped: " + uri);
        Imageuri = uri.toString();
        sharedPre("Imageuri",Imageuri);
        Glide.with(this).load(uri).transform(new CircleTransform(this)).into(meSetHeadImageLogo);
        mCropParams = null;
        mCropParams = new CropParams(this);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        CropHelper.handleResult(this, requestCode, resultCode, data);
        if (requestCode == 1) {
        }
    }

    @Override
    public void onCompressed(Uri uri) {
        // Compressed uri
        Log.i("TAG", "onCompressed: " + uri);
        Imageuri = uri.toString();
        sharedPre("Imageuri",Imageuri);
        Glide.with(this).load(uri).transform(new CircleTransform(this)).into(meSetHeadImageLogo);
        mCropParams = null;
        mCropParams = new CropParams(this);
    }

    @Override
    public void onCancel() {
        Toast.makeText(this, "Crop canceled!", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onFailed(String message) {
        Toast.makeText(this, "Crop failed: " + message, Toast.LENGTH_LONG).show();
    }

    @Override
    public void handleIntent(Intent intent, int requestCode) {
        startActivityForResult(intent, requestCode);
    }

    @Override
    public CropParams getCropParams() {
        return mCropParams;
    }
    @Override
    protected void onDestroy() {
        CropHelper.clearCacheDir();

        super.onDestroy();
    }
    public void sharedPre(String string,String value){
        SharedPreferences sp = getSharedPreferences("user",MODE_PRIVATE);
        Editor pen = sp.edit();
        pen.putString(string,value);
        pen.commit();
    }
    public void getData(String string){
        SharedPreferences sp = getSharedPreferences("user", MODE_PRIVATE);
        String string1 = sp.getString(string, null);
        switch (string) {
            case "Imageuri":
                if(string1!=null){
                    Glide.with(MeSetActivity.this).load(string1).into(meSetHeadImageLogo);
                }else{
                    meSetHeadImageLogo.setImageResource(R.mipmap.ic_launcher);
                }
                break;
            case "username":
                if(string1!=null){
                    meHeadSetDetilNamedetil.setText(string1);
                }else{
                    meHeadSetDetilNamedetil.setText(string1);
                }
                break;
            case "usersex":
                if(string1!=null){
                    meHeadSetDetilSexdetil.setText(string1);
                }else{
                    meHeadSetDetilSexdetil.setText(string1);
                }
                break;
            case "userdetil":
                if(string1!=null){
                    meHeadSetDetilPersondetil.setText(string1);
                }else{
                    meHeadSetDetilPersondetil.setText("啦啦啦~");
                }
                break;
        }
    }
}
